var express=require('express');
var fs = require('fs');
var config=require('./config');
var routes=require('./routes');
var User=require('./model/User');
var Time=require('./utils/Time');


var app=express();
//系统日志
var date=new Date();
var logPath='./log/'+date.getFullYear()+'.'+(date.getMonth()+1)+'.'+date.getDate()+'.';
var accessLogfile = fs.createWriteStream(logPath+'access.log', {flags: 'a'});
var errorLogfile = fs.createWriteStream(logPath+'error.log', {flags: 'a'});

//设置视图模板目录
app.set('views',__dirname+'/view');
//设置视图模板解析引擎
app.set('view engine','ejs');
//设置静态文件目录
app.use(express.static(__dirname+'/public'));
app.use(express.favicon(__dirname+'/public/favicon.ico'));
app.use(express.logger({stream: accessLogfile}));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('fanfou'));
app.use(express.session({secret:'fanfou'}));

//拦截器,未登录自动跳转到登陆页面
app.use(function(req,res,next){
	var url=req.originalUrl;
	//是否登陆判断
	if(url!='/login'&&url.indexOf('/api')==-1&&!req.session.user){
		return res.redirect("/login");
	}
	//判断是否是管理员
	if(url.indexOf('/admin')!=-1&&req.session.user.isAdmin==0){
		return res.redirect("/");
	}
	next();
})

//错误日志
app.use(function(err, req, res, next){
    var meta = '[' + new Date() + '] ' + req.url + '\n';
    errorLogfile.write(meta + err.stack + '\n');
    next();
});

//路由设置
routes(app);

app.listen(config.port);
console.log('Server Started | Running at Port:'+config.port+" | Time:"+Time.getNow());